%% 假设指挥部的坐标是(0, 0)
global S % 观测点坐标Ns*2，最上面补一个指挥部的坐标(0,0)
global Ns % 观测点数目
global vmax % 最大速度
global Tmax % 最大时间
global dmax % 最大距离
global tDelaymax % 最大平均延时时间
global Tcharge % 充电时间
global distmax % 最远接收距离
global arr
fd=fopen('log');
arr=textscan(3,'%s','Delimiter','\n','MultipleDelimsAsOne',1);
fclose(fd);
arr=arr{1};
fun=@(x) textscan(x,'%d','Delimiter',',','CollectOutput',1);
arr=cellfun(fun,arr,'UniformOutput',0);
fun=@(x) double(x{1});
arr=cellfun(fun,arr,'UniformOutput',0);
Ns=arr{1};
vmax=20*3.6;dmax=30;tDelaymax=15/60;Tmax=0.4;Tcharge=1.75;distmax=2;
rng('shuffle');
[x,y]=pol2cart(rand(Ns,1)*2*pi,rand(Ns,1)*15);
S=cat(2,x,y);
nside=20;
load('arr.mat');

%%
sidelen=2*distmax*sin(2*pi/(2*nside));
sparray=repmat(polyshape([0 0 1],[1 0 0]),1,Ns);
for i=1:Ns
    sparray(i)=nsidedpoly(nside,'center',S(i,:),'sidelength',sidelen);
end
close all;
xy=15*exp(1j*2*pi/100*(0:100));
plot(xy,'black');
hold on;
plot(sparray);
plot(S(:,1),S(:,2),'.','color','black');
hold off;
axis equal

%%
[ushape,uspid]=union(sparray);
nrgn=ushape.NumRegions;
spindex=cell(nrgn,1);
uspid(uspid==0)=[];
nanindex=[0;find(isnan(uspid));numel(uspid)+1];
for i=1:nrgn
    spindex{i}=unique(uspid(nanindex(i)+1:nanindex(i+1)-1));
end

%%
rgndots=cell(nrgn,1);
for i=1:nrgn
    len=numel(spindex{i});
    dividenum=numel(arr{len});
    rgndots{i}=cell(dividenum,1);
    for j=1:dividenum
        rgndots{i}{j}=digui(sparray(spindex{i}),arr{len}{j});
    end
    rgndots{i}=reshape(vertcat(rgndots{i}{:}),[],1);
end

dnum=cellfun(@(c) cellfun(@(x) sum((sqrt(sum(x.^2,2))>13.5)+2),c),rgndots,'UniformOutput',0);
[minarray,minindex]=cellfun(@(x) min(x),dnum);
minplane=sum(minarray);
mindots=cell(nrgn,1);
for i=1:nrgn
    mindots{i}=rgndots{i}{minindex(i)};
end
mindots=vertcat(mindots{:});
mindots=mindots(:,1)+1j*mindots(:,2);

%%
close all;
figure;
hold on;
xy=15*exp(1j*2*pi/100*(0:100));
plot(xy,'black');
plot(sparray);
plot(S(:,1),S(:,2),'.','color','black');
axis equal
plot(0,0,'pr','MarkerFaceColor','red','markersize',9);
plot(mindots,'^','color','#A2142F','MarkerFaceColor','#A2142F');
hold off;
